package org.jeecg.modules.assets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.assets.entity.*;
import org.jeecg.modules.assets.mapper.AssetsReturnItemMapper;
import org.jeecg.modules.assets.service.*;
import org.jeecg.modules.job.AssetsJob;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 设备归还单管理
 * @Author: jeecg-boot
 * @Date: 2024-11-09
 * @Version: V1.0
 */
@Service
public class AssetsReturnItemServiceImpl extends ServiceImpl<AssetsReturnItemMapper, AssetsReturnItem> implements IAssetsReturnItemService {

    @Autowired
    private IAssetsItemService assetsItemService;
    @Autowired
    private IAssetsApplyItemService assetsApplyItemService;
    @Autowired
    private IAssetsInfoService assetsInfoService;
    @Autowired
    private IAssetsApplyDeptService assetsApplyDeptService;

    @Autowired
    AssetsJob assetsJob;

    /**
     * 获取当前归还单状态
     *
     * @param assetsReturnItem
     */
    @Override
    public void saveReturnItem(AssetsReturnItem assetsReturnItem) {
        QueryWrapper qw = new QueryWrapper();
        //只取后六位
        qw.eq("asset_coding", assetsReturnItem.getAssetCoding().substring(assetsReturnItem.getAssetCoding().length() - 6));
        //获取对应的资产
        AssetsItem one = assetsItemService.getOne(qw);
        if (StringUtils.isNotEmpty(assetsReturnItem.getStatus())) {
            one.setStatus(assetsReturnItem.getStatus());
        }
        //判断资产状态
        if (Objects.equals(one.getApplyStatus(), 0)) {
            //获取对应的领用单
            AssetsApplyItem assetsApplyItem = assetsApplyItemService.getById(one.getApplyId());
            //更新领用单状态
            assetsApplyItem.setApplyStatus("2");
            assetsApplyItemService.updateById(assetsApplyItem);
            AssetsReturnItem  saveAssetsItem = new AssetsReturnItem();
            BeanUtils.copyProperties(one, saveAssetsItem);
            //归还人
            saveAssetsItem.setReturnUser(assetsApplyItem.getApplyUser());
            saveAssetsItem.setReturnUserId(assetsApplyItem.getApplyUserId());
            //插入资产id
            saveAssetsItem.setAssetsId(one.getId());
            saveAssetsItem.setRemark(assetsReturnItem.getRemark());
            saveAssetsItem.setReturnDate(DateFormatUtils.format(new java.util.Date(), "yyyy-MM-dd HH:mm:ss"));
            saveAssetsItem.setLender(assetsApplyItem.getLender());
            saveAssetsItem.setReturnUser(assetsApplyItem.getLender());
            saveAssetsItem.setDeptName(assetsApplyItem.getDeptName());
            saveAssetsItem.setDeptId(assetsApplyItem.getDeptId());
            saveAssetsItem.setId(null);
            this.save(saveAssetsItem);
            //归还时，需要更新设备状态
            //更新借用单位为空
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", one.getId());
            updateWrapper.set("lender", "");
            updateWrapper.set("dept_name", "");
            updateWrapper.set("dept_id", null);
            //更新设备领用状态
            updateWrapper.set("apply_status", 1);
            if(assetsReturnItem.getStatus()!=null){
                updateWrapper.set("status", assetsReturnItem.getStatus());
            }
            updateWrapper.set("return_id", assetsReturnItem.getId());
            assetsItemService.update(null,updateWrapper);
            //判断是否存在借用单位，如果存在则数量减一
            if (assetsApplyItem.getDeptId()!=null) {
                AssetsApplyDept byId = assetsApplyDeptService.getById(assetsApplyItem.getDeptId());
                byId.setNum((byId.getNum()==null?1:byId.getNum()) - 1);
                //获取设备分类
                assetsApplyDeptService.updateById(byId);
                //todo 推送工具箱
            }
            //归还成功，更改设备可用库存数量
            //设备可用数加1
           // assetsItemService.updateById(one);
            QueryWrapper one1 = new QueryWrapper();
            one1.eq("asset_name", one.getAssetName());
            AssetsInfo byId = assetsInfoService.getOne(one1);
            byId.setStoreNum(byId.getStoreNum() + 1);
            byId.setStoreUseNum(byId.getStoreUseNum() + 1);
            assetsInfoService.updateById(byId);
            assetsJob.startWron();

        } else {
            throw new RuntimeException("设备在库，无法归还！");
        }

        //获取当前设备状态


    }

    @Override
    @Transactional(rollbackFor = Exception.class)

    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        StringBuilder stringBuilder = new StringBuilder();
        Integer count = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<AssetsReturnItem> list = ExcelImportUtil.importExcel(file.getInputStream(), AssetsReturnItem.class, params);
                stringBuilder.append("本次共导入：[" + list.size() + "]");
                for (AssetsReturnItem assetsItem : list) {
                    //插入资产明细
                    saveReturnItem(assetsItem);
                    count++;

                }
                stringBuilder.append("成功：[" + count + "]");
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }

        }
        return Result.ok(stringBuilder.toString());

    }
}
